package com.shaoyu.elasticsearch.controller;

import com.alibaba.fastjson.JSON;
import com.shaoyu.elasticsearch.dao.ElasticSearchIndexRepository;
import com.shaoyu.elasticsearch.entity.ElasticsearchIndex;
import com.shaoyu.elasticsearch.entity.Product;
import com.shaoyu.elasticsearch.service.ElasticSearchSearchService;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/rest")
public class IndexController {

    @Autowired
    ElasticSearchSearchService searchService;
    @Autowired
    ElasticSearchIndexRepository repository;

        @RequestMapping("/searchProduct")
        public Object index(HttpServletRequest request){
            List<ElasticsearchIndex> list = repository.findAll();
            List<Product>productList = new ArrayList<>();
            Product p = new Product();
            Map<String, String[]> map = request.getParameterMap();
            System.out.println(JSON.toJSONString(map));
            p.setName(request.getParameter("keyword"));
            double price = Double.parseDouble(request.getParameter("price"));
            p.setPrice(price);
            SearchResponse response = searchService.search(list,p);
            Iterator<SearchHit> iterator = response.getHits().iterator();
            while(iterator.hasNext()){
                SearchHit hit = iterator.next();
                String  source = hit.getSourceAsString();
                Product result = JSON.parseObject(source,Product.class);
                productList.add(result);
            }
        return productList;
    }
}
